<template>
  <view>
    <view class="sou">
      <input type="text" placeholder="请输入商品名称" />
    </view>
    <view class="shop">
      <view v-for="shop in shoptitle" :key="shop.id" class="shop-item">
        <image :src="shop.imgUrl" />
        <view class="shop-right">
          <view class="shop-one">{{ shop.name }}</view>
          <view class="shop-two">
            月售：{{ shop.sales }} &nbsp;
            起送：{{ shop.expressLimit }} &nbsp;
            基础运费：{{ shop.expressPrice }}
          </view>
          <view class="shop-three">{{ shop.slogan }}</view>
        </view>
      </view>
    </view>
    <view class="goods">
      <view class="left">
        <view @click="all()" :class="{active: activeTab === 'all'}">全部商品</view>
        <view @click="seckill()" :class="{active: activeTab === 'seckill'}">秒杀</view>
        <view @click="fruit()" :class="{active: activeTab === 'fruit'}">新鲜水果</view>
      </view>
      <view class="right-container">
        <view class="right" v-for="(item, index) in product" :key="item.id">
          <image :src="item.imgUrl" style="width:65px;height:65px"/>
          <view class="product-info">
            <view class="name">{{ item.name }}</view>
            <view class="sales">月售{{ item.sales }}件</view>
            <view class="price">
              <view class="new_old">
                <view class="new">¥{{ item.price }}</view>
                <view class="old">¥{{ item.oldPrice }}</view>
              </view>
              <view class="sum">
                <button @click.stop="decreaseQuantity(index)" class="quantity-btn">-</button>
                <view class="quantity">{{ getCartQuantity(item.id) }}</view>
                <button @click.stop="increaseQuantity(index)" class="quantity-btn">+</button>
              </view>
            </view>
          </view>
        </view>
      </view>
    </view>
    <!-- 购物车组件，通过 showCart 控制显示隐藏 -->
    <view v-if="showCart" class="cart-modal">
      <view class="cart-body">
        <view v-if="cartItems.length === 0" class="null">
          <text>当前购物车为空</text>
          <view @click="closeCart" style="color:red;">关闭</view>
        </view>
        <view v-else class="card">
          <view class="header">
            <!-- 修改为 checkbox-group -->
            <checkbox-group @change="toggleAllCheck">
              <checkbox :checked="isAllChecked" />全选
            </checkbox-group>
            <view></view>
            <view class="cart-header">
              <view @click="closeCart">关闭</view>
            </view>
            <button @click="clearCart">清空购物车</button>
          </view>
          <view class="body" v-for="(item, index) in cartItems" :key="item.id">
            <!-- 修改为 checkbox-group -->
            <checkbox-group @change="(e) => toggleCheck(index, e)">
              <checkbox :checked="item.checked" />
            </checkbox-group>
            <image :src="item.img" style="width:50px;height:50px;"/>
            <view class="product-info">
              <view class="name">{{ item.name }}</view>
              <view class="sales">月售{{ item.sales }}件</view>
              <view class="price">
                <view class="new_old">
                  <view class="new">￥{{ item.price }}</view>
                  <view class="old">￥{{ item.oldPrice }}</view>
                </view>
                <view class="sum">
                  <button @click="dele(index)">-</button>
                  <view style="margin:5px;">{{item.quantity }}</view>
                  <button @click="add(index)">+</button>
                </view>
              </view>
            </view>
          </view>
          <view class="foot">
            <view class="total">总计：<text>￥{{num}}</text></view>
            <button @click="checkout" class="button">去结算({{selectedCount}})</button>
          </view>
        </view>
      </view>
    </view>
    <!-- 购物车底部栏 -->
    <view class="cart-footer" v-if="cartTotal > 0">  
      <view class="cart-icon">
        <image src="/static/imgs/购物篮.png" @click="gouwulan" style="width:24px;height:24px"/>
        <view class="badge">{{ cartTotal }}</view>
      </view>
      <view class="cart-info">
        <view class="total-price">¥{{ totalPrice }}</view>
        <view class="delivery-info">另需配送费¥5</view>
      </view>
      <button class="checkout-btn" @click="checkout">去结算</button>
    </view>
  </view>
</template>

<script>
import config from '../config.js';
import axios from 'axios';
export default {
  data() {
    return {
      superid: null,
      shoptitle: [],
      product: [],
      activeTab: 'all',
      cartItems: [],
      showCart: false, // 控制购物车组件的显示隐藏
    };
  },
  computed: {
    cartTotal() {
      return this.cartItems.reduce((total, item) => total + item.quantity, 0);
    },
    totalPrice() {
      return this.cartItems.reduce((total, item) => total + (item.price * item.quantity), 0).toFixed(2);
    },
    num() {
      return this.cartItems
        .filter(item => item.checked)
        .reduce((total, item) => {
          return total + item.price * item.quantity;
        }, 0)
        .toFixed(2);
    },
    isAllChecked() {
      return this.cartItems.length > 0 && this.cartItems.every(item => item.checked);
    },
    selectedCount() {
      return this.cartItems.filter(item => item.checked).length;
    }
  },
  onLoad(options) {
    this.superid = options.id;
    this.shop();
    this.all();
    this.loadCart();
  },
  methods: {
    shop() {
      uni.request({
        url: config.api_host+`/data?id=${this.superid}`,
        success: (res) => {
          this.shoptitle = res.data;
        },
      });
    },
    all() {
      this.activeTab = 'all';
      uni.request({
        url: config.api_host+`/product?shopId=${this.superid}`,
        success: (res) => {
          this.product = res.data;
        },
      });
    },
    seckill() {
      this.activeTab = 'seckill';
      uni.request({
        url: config.api_host+`/kill?shopId=${this.superid}`,
        success: (res) => {
          this.product = res.data;
        },
      });
    },
    fruit() {
      this.activeTab = 'fruit';
      uni.request({
        url:config.api_host+ `/Fruit?shopId=${this.superid}`,
        success: (res) => {
          this.product = res.data;
        },
      });
    },
    loadCart() {
      uni.request({
        url:config.api_host+ '/carts',
        success: (res) => {
          this.cartItems = res.data.map(item => ({
            ...item,
            checked: false
          }));
        }
      });
    },
    gouwulan() {
      this.showCart = true;
    },
    closeCart() {
      this.showCart = false;
    },
    getCartQuantity(productId) {
      const item = this.cartItems.find(i => i.productId === productId);
      return item? item.quantity : 0;
    },
    increaseQuantity(index) {
      const item = this.product[index];
      const cartItem = this.cartItems.find(i => i.productId === item.id);
      
      if (cartItem) {
        // 更新数量
        uni.request({
          url: config.api_host+`carts/${cartItem.id}`,
          method: 'PATCH',
          data: { quantity: cartItem.quantity + 1 },
          success: () => {
            this.loadCart();
          }
        });
      } else {
        // 添加到购物车
        uni.request({
          url: config.api_host+'/carts',
          method: 'POST',
          data: {
            shopid: item.shopId,
            productId: item.id,
            name: item.name,
            img: item.imgUrl,
            sales: item.sales,
            price: item.price,
            oldPrice: item.oldPrice,
            quantity: 1
          },
          success: () => {
            uni.showToast({
              title: '已添加',
              icon: 'success'
            });
            this.loadCart();
          }
        });
      }
    },
    decreaseQuantity(index) {
      const item = this.product[index];
      const cartItem = this.cartItems.find(i => i.productId === item.id);
      
      if (cartItem) {
        if (cartItem.quantity > 1) {
          // 减少数量
          uni.request({
            url: config.api_host+`/carts/${cartItem.id}`,
            method: 'PATCH',
            data: { quantity: cartItem.quantity - 1 },
            success: () => {
              this.loadCart();
            }
          });
        } else {
          // 从购物车移除
          uni.request({
            url: config.api_host+`/carts/${cartItem.id}`,
            method: 'DELETE',
            success: () => {
              this.loadCart();
            }
          });
        }
      }
    },
    add(index){
      this.cartItems[index].quantity++
    },
    dele(index){
      if (this.cartItems[index].quantity > 1) {
        this.cartItems[index].quantity--;
      } else if(this.cartItems[index].quantity === 1){
        this.cartItems.splice(index, 1)
      }
    },
    clearCart() {
      axios.get(api_host+"/carts")
        .then(res => {
          const items = res.data;
          const deletePromises = items.map(item => {
            return axios.delete(api_host+`/carts/${item.id}`)
          });
          return Promise.all(deletePromises);
        })
        .then(() => {
          this.cartItems = []; // 清空本地数据
          uni.showToast({
            title: '清除成功',
          })
        })
        .catch(err => {
          console.error('清空购物车失败:', err);
          uni.showToast({
            title: '清除失败',
            icon: 'none'
          })
        });
    },
    checkout() {
      const selectedItems = this.cartItems.filter(item => item.checked);
      if(selectedItems.length === 0) {
        uni.showToast({
          title: '请选择要结算的商品',
          icon: 'none'
        });
        return;
      }
      uni.navigateTo({
        url: `/pages/dingdan/suredingdan?selectedItems=${JSON.stringify(selectedItems)}`
      });
    },  
    toggleCheck(index, e) {
      // 获取当前checkbox的选中状态
      const isChecked = e.detail.value.length > 0;
      // 使用Vue.set确保响应式更新
      this.$set(this.cartItems[index], 'checked', isChecked);
    },
    toggleAllCheck(e) {
      // 获取全选checkbox的选中状态
      const isChecked = e.detail.value.length > 0;
      // 创建新数组确保响应式更新
      this.cartItems = this.cartItems.map(item => ({
        ...item,
        checked: isChecked
      }));
    },
  },
};
</script>

<style scoped>
/* 搜索框样式 */
.sou {
  height: 40px;
  width: 85%;
  background-color: #f0f0f0;
  border-radius: 20px;
  padding: 0 15px;
  display: flex;
  align-items: center;
  margin: 10px auto;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}
.sou input {
  border: none;
  outline: none;
  flex: 1;
  font-size: 14px;
  padding: 0 10px;
}

/* 店铺列表样式 */
.shop {
  margin: 20px;
}
.shop-item {
  height: 100px;
  display: flex;
  border-bottom: 1px solid #e0e0e0;
  padding: 15px 0;
  transition: background-color 0.3s ease;
}
.shop-item:hover {
  background-color: #f9f9f9;
}
.shop-item image {
  width: 70px;
  height: 70px;
  margin-right: 15px;
  border-radius: 10px;
  object-fit: cover;
}
.shop-right {
  display: flex;
  flex-direction: column;
  justify-content: space-between;
}
.shop-one {
  font-size: 20px;
  font-weight: bold;
  color: #333;
}
.shop-two {
  font-size: 14px;
  color: #666;
}
.shop-three {
  color: #ff5a5f;
  font-size: 14px;
}

/* 商品分类和商品列表样式 */
.goods {
  display: flex;
  margin-top: 10px;
}
.left {
  width: 20%;
  padding: 10px;
  background-color: #f5f5f5;
  box-shadow: 2px 0 6px rgba(0, 0, 0, 0.08);
}
.left view {
  padding: 15px 0;
  margin-bottom: 10px;
  text-align: center;
  font-size: 15px;
  color: #666;
  cursor: pointer;
  transition: all 0.3s ease;
  border-radius: 5px;
}
.left view.active {
  color: #fff;
  font-weight: bold;
  background-color: #ff5a5f;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}
.left view:hover {
  background-color: #f0f0f0;
  color: #333;
}
.right-container {
  width: 80%;
  overflow-y: auto;
  padding-bottom: 60px; /* 为购物车底部栏留出空间 */
}
.right {
  display: flex;
  padding: 15px;
  border-bottom: 1px solid #eaeaea;
  transition: background-color 0.3s ease;
}
.right:hover {
  background-color: #f9f9f9;
}
.right image {
  width: 70px;
  height: 70px;
  margin-right: 15px;
  border-radius: 10px;
  object-fit: cover;
}
.product-info {
  flex: 1;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
}
.name {
  font-size: 18px;
  font-weight: bold;
  color: #333;
  margin-bottom: 5px;
}
.sales {
  font-size: 13px;
  color: #999;
  margin-bottom: 10px;
}
.price {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.new_old {
  display: flex;
  align-items: baseline;
}
.new {
  font-size: 16px;
  color: #ff5a5f;
  margin-right: 8px;
}
.old {
  font-size: 12px;
  color: #999;
  text-decoration: line-through;
}
.sum {
  display: flex;
  align-items: center;
}
.quantity-btn {
  width: 28px;
  height: 28px;
  line-height: 28px;
  text-align: center;
  padding: 0;
  border-radius: 50%;
  background-color: #f0f0f0;
  border: none;
  font-size: 16px;
  transition: background-color 0.3s ease;
}
.quantity-btn:hover {
  background-color: #e0e0e0;
}
.quantity {
  margin: 0 8px;
  min-width: 20px;
  text-align: center;
  font-size: 16px;
  color: #333;
}

/* 购物车模态框样式 */
.cart-modal {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000;
}
.cart-modal-content {
  background-color: #fff;
  width: 80%;
  max-width: 600px;
  border-radius: 10px;
  overflow: hidden;
}
.cart-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 15px;
  border-bottom: 1px solid #e0e0e0;
  background-color: #f5f5f5;
}
.cart-header view:first-child {
  cursor: pointer;
  font-size: 16px;
  color: #666;
}
.cart-body {
  padding: 15px;
  background-color: white;
}
.null {
  text-align: center;
  font-size: 16px;
  color: #999;
  padding: 50px 0;
}
.card {
  width: 100%;
}
.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 10px 0;
  border-bottom: 1px solid #e0e0e0;
}
.body {
  display: flex;
  align-items: center;
  padding: 15px 0;
  border-bottom: 1px solid #e0e0e0;
}
.body image {
  width: 60px;
  height: 60px;
  margin-right: 15px;
  border-radius: 10px;
  object-fit: cover;
}
.foot {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 15px;
  background-color: #f5f5f5;
  border-top: 1px solid #e0e0e0;
}
.total {
  font-size: 18px;
  font-weight: bold;
  color: #333;
}
.total text {
  color: #ff5a5f;
}
.button {
  background-color: #ff5a5f;
  color: #fff;
  border: none;
  padding: 10px 20px;
  border-radius: 5px;
  font-size: 14px;
  cursor: pointer;
  transition: background-color 0.3s ease;
}
.button:hover {
  background-color: #ff3b41; /* 调整按钮 hover 颜色 */
}

/* 购物车底部栏样式 */
.cart-footer {
  height: 60px;
  background-color: #fff;
  display: flex;
  align-items: center;
  padding: 0 20px;
  box-shadow: 0 -2px 8px rgba(0, 0, 0, 0.1);
  position: fixed;
  bottom: 0;
  left: 0;
  width: 100%;
  z-index: 100;
}
.cart-icon {
  position: relative;
  margin-right: 20px;
}
.badge {
  position: absolute;
  top: -6px;
  right: -6px;
  background-color: #ff5a5f;
  color: #fff;
  border-radius: 50%;
  width: 20px;
  height: 20px;
  font-size: 12px;
  display: flex;
  justify-content: center;
  align-items: center;
}
.cart-info {
  flex: 1;
}
.total-price {
  font-size: 18px;
  font-weight: bold;
  color: #333;
}
.total-price span {
  color: #ff5a5f;
}
.delivery-info {
  font-size: 14px;
  color: #999;
  margin-top: 5px;
}
.checkout-btn {
  background-color: #ff5a5f;
  color: #fff;
  border: none;
  padding: 10px 25px;
  border-radius: 20px;
  font-size: 14px;
  cursor: pointer;
  transition: background-color 0.3s ease;
}
.checkout-btn:hover {
  background-color: #ff3b41; /* 调整按钮 hover 颜色 */
}

/* 购物车中勾选框样式 */
checkbox {
  -webkit-appearance: none; /* 去除默认样式 */
  appearance: none;
  width: 20px;
  height: 20px;
  border: 2px solid #ccc;
  border-radius: 3px;
  outline: none;
  cursor: pointer;
  margin-right: 10px;
}
checkbox:checked {
  background-color: #007aff; /* 选中时的背景色 */
  border-color: #007aff;
  background-image: url('data:image/svg+xml;charset=utf8,%3Csvg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 20 20"%3E%3Cpath fill="none" stroke="%23fff" stroke-linecap="round" stroke-linejoin="round" stroke-width="3" d="M6 10l4 4 8-8"/%3E%3C/svg%3E'); /* 选中时的对勾图标 */
  background-size: 12px;
  background-position: center;
  background-repeat: no-repeat;
}

/* 调整购物车商品数量数字的样式 */
.body.view.quantity {
  font-size: 16px;
  color: #333;
  min-width: 20px;
  text-align: center;
}
</style>    